/* Includes */
#include "include/parser.h"
#include "include/archiver.h"
#include "include/dynamic_list.h"

char * am_get_line(char * buffer, int line)
{
	int i = 0;	/* where to read from/to */
	int x = 0;	/* How many chars read total */
	int linesr = 0; /* How many lines its read */
	int linest = 0; /* Total number of lines in buffer */
	dynlist_t * ini = NULL;
	char * charread = NULL;
	char * result = NULL;
	
	/* Count the total number of lines in buffer */
	for(int i = 0; i < strlen(buffer); i++) {
		if(buffer[i] == '\n')
			linest++;
	}			
	
	/* Return 0 if the user tries to access a line that doesent exist */
	if(line > linest)
		return 0;
	
	/* Create a dynamic list to put the chars in */
	ini = dynlist_create("Ini Characters", free);

	/* Keep skipping lines until the right count */
	for(i = 0; i < strlen(buffer); i++) {
		if(line == linesr)
			break;	
		if(buffer[i] == '\n')
			linesr++;
	}

	/* Read chars from i in buffer until \n or \r */
	for(i = i; i < strlen(buffer); i++) {
		if(buffer[i] != '\n' && buffer[i] != '\r') { 
			charread = malloc(2);
			charread[0] = buffer[i];
			charread[1] = 0;
			/* putting buffer[i] in the dynamic list */
			dynlist_push(ini, charread);
			x++;
		} else break;
	}
	
	/* Take char by char from the list, put it in result */
	result = malloc(x+1);
	memset(result, 0, x+1);
	for(int i = 0; i < x; i++) {
		strcat(result, dynlist_get(ini, i));
	}
	
	/* Free */
	dynlist_free(&ini);

	return result;
}

int char_str_trim(char ch, char * trimlist)
{
	/* Check if the ch is the same as trimlist[i] */
	for(int i = 0; i < strlen(trimlist); i++) {
		if((ch == trimlist[i]))
			return 1;
	}
	
	return 0;
}

char * am_str_trim(char * string, char * trimlist)
{
	int i = 0, x = 0;

	/* Trim number of characters from left */
	for(i = 0; i < strlen(string); i++) {
		if(string[i] == ' ' || string[i] == '\t') {
			continue;
		} else if(char_str_trim(string[i], trimlist)) {
			continue;
		} else break;

	}
	
	/* Trim number of characters from right */
	for(x = strlen(string)-1; x >= 0; x--)
	{
		if(string[x] == ' ' || string[x] == '\t') {
			continue;
		} else if(char_str_trim(string[x], trimlist)) {
			continue;
		} else break;
	}
	
	/* Be sure that the string is not empty */
	if(i >= x)
		return 0;
	
	/* Copy the final trimmed string to result */
	char * result = malloc(x-i+1);
	memcpy(result, string+i, x-i);
	result[x-i] = 0;
	
	return result;
}

char * am_parse_ini_val(char * buffer, char * group, char * value)
{
	int i = 0;
	char * string = NULL;
	char * result = NULL;
	
	while((string = am_get_line(buffer, i))) {
		char * temp = am_str_trim(string, "[]");
		printf("%s\n", temp);
		if(temp == group) {
			/* Read value here */
		}
		free(temp);
		free(string);
		i++;
	}
	
	printf("test\a");
	

	return result;
}

